package com.example.tangjiangxu.photowallfallsdemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.util.LruCache;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;

/**
 * Created by Administrator on 2017/3/28 0028.
 * 图片加载器
 */
public class ImageLoader {
    private static final String TAG = "ImageLoader";

    private static LruCache<String, Bitmap> mMemoryCache;
    private static ImageLoader instance;

    public static ImageLoader getInstance() {
        if (instance == null) {
            instance = new ImageLoader();
        }
        return instance;
    }

    private ImageLoader() {
        //获取到可用内存的最大值，使用内存超出这个值会引起OutOfMemory异常
        //LruCache通过构造函数传入缓存值，以kb为单位
        int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        //使用最大可用内存值的1/8作为缓存的大小
        int cacheSize = maxMemory / 8;
        Log.e(TAG, "ImageCache: cacheSize:" + (cacheSize / 1024) + "Mb");
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                Log.e(TAG, "sizeOf: "  + (bitmap.getByteCount() *1.0 / 1024 / 1024) + "Mb");
                //重写此方法来衡量每张图片的大小，不是返回图片数量
                return bitmap.getByteCount() / 1024;
            }
        };
    }

    /**
     * 把bitmap加入到缓存中
     * @param key
     * @param bitmap
     */
    public static void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemoryCache(key)  == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    /**
     * 从缓存里获得图片
     * @param key
     * @return
     */
    public static Bitmap getBitmapFromMemoryCache(String key) {
        return mMemoryCache.get(key);
    }

    /**
     * 设置图片
     * @param imageUrl
     * @param imageView
     */
    public static void setImageView(String imageUrl, ImageView imageView) {
        Bitmap bitmap = getBitmapFromMemoryCache(imageUrl);
        if (bitmap != null) {
            Log.e(TAG, "getView 缓存中找到:" + imageUrl );
            imageView.setImageBitmap(bitmap);
        } else {
            imageView.setImageResource(R.mipmap.ic_launcher);
        }
    }
    /**
     * 从本地获取照片
     * @param context
     * @param resId
     * @param reqH
     * @param reqW
     * @return
     */
    private static Bitmap loadImageFromLocal(Context context, int resId, int reqH, int reqW) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        //inJustDecodeBounds设置为true, 不进行真正获取图片
        options.inJustDecodeBounds = true;
        //进行图片取样，只获取宽高等参数，不进行真正取样
        BitmapFactory.decodeResource(context.getResources(), resId, options);
        //根据option、所需宽高，算出缩放比例
        options.inSampleSize = calculateinSampleSize(options, reqH, reqW);
        //inJustDecodeBounds为false，真正获取图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(context.getResources(), resId, options);

    }

    /**
     * 计算缩放比例
     * @param options
     * @param reqH
     * @param reqW
     * @return
     */
    private static int calculateinSampleSize(BitmapFactory.Options options, int reqH, int reqW) {
        int sample = 1;
        int height = options.outHeight;
        int widht = options.outWidth;
        Log.e(TAG, "calculateinSampleSize: height:" + height + ",width:" + widht);
        if (height > reqH && widht > reqW) {
            double ratioH = height * 1.0 / reqH;
            double ratioW = widht * 1.0 / reqW;
            sample = (int) (ratioW > ratioH ? Math.round(ratioW) : Math.round(ratioH));
        }
        Log.e(TAG, "calculateinSampleSize: sample:" + sample);
        return sample;
    }

    /**
     * 从流中获取照片
     * @param reqH
     * @param reqW
     * @return
     */
    public static Bitmap loadImageFromStream(ByteArrayOutputStream baos, int reqH, int reqW) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        //inJustDecodeBounds设置为true, 不进行真正获取图片
        options.inJustDecodeBounds = true;
        //进行图片取样，只获取宽高等参数，不进行真正取样
        BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length, options);
        //根据option、所需宽高，算出缩放比例
        options.inSampleSize = calculateinSampleSize(options, reqH, reqW);
        //inJustDecodeBounds为false，真正获取图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length, options);

    }

    /**
     * 计算缩放比例
     * @param options
     * @param reqW
     * @return
     */
    private static int calculateinSampleSize(BitmapFactory.Options options, int reqW) {
        int sample = 1;
        int widht = options.outWidth;
        if (widht > reqW) {
            sample = (int) Math.round(widht * 1.0 / reqW);
        }
        return sample;
    }

    /**
     * 从文件中获取照片
     * @param reqW
     * @return
     */
    public static Bitmap loadImageFromFilePath(String filePath, int reqW) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        //inJustDecodeBounds设置为true, 不进行真正获取图片
        options.inJustDecodeBounds = true;
        //进行图片取样，只获取宽高等参数，不进行真正取样
        BitmapFactory.decodeFile(filePath, options);
        //根据option、所需宽高，算出缩放比例
        options.inSampleSize = calculateinSampleSize(options, reqW);
        //inJustDecodeBounds为false，真正获取图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);

    }


}
